<%@ page pageEncoding="UTF-8"%>
<%@ page language="java" import="java.util.*"  import="java.util.regex.Matcher"
         import="java.util.regex.Pattern,com.alibaba.fastjson.TypeReference" %>
<%@ page import="com.tianxiabuyi.Message" %>
<%@ page import="com.tianxiabuyi.Input" %>
<%@ page import="com.tianxiabuyi.model.pojo.Hospital" %>
<%@ page import="com.tianxiabuyi.persist.QBuilder" %>
<%@ page import="com.tianxiabuyi.model.pojo.Dept" %>
<%@ page import="com.tianxiabuyi.model.pojo.User" %>
<%@ page import="com.tianxiabuyi.persist.DBTools" %>
<%@ page import="static com.tianxiabuyi.utils.ConstantUtil.STATUS_ENABLE" %>
<%@ page import="com.tianxiabuyi.persist.Where" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="com.tianxiabuyi.model.pojo.News" %>
<%@ page import="com.tianxiabuyi.utils.Tools" %>
<%@ page import="com.tianxiabuyi.utils.JSONUtil" %>
<%@ page import="com.tianxiabuyi.utils.ImageUtil" %>
<%@ page import="static com.tianxiabuyi.utils.ConstantUtil.STATUS_DISABLE" %>
<%@ page import="org.jsoup.select.Elements" %>
<%@ page import="org.jsoup.Jsoup" %>

<%@ page import="com.tianxiabuyi.model.pojo.Survey" %>
<%@ page import="com.tianxiabuyi.model.pojo.SurveyOptions" %>
<%!
    public final static String PATTERN = "<img src=\'http://[^>]*?>";

    // 获取图片的像素
    public static String pixel (String imgStr) {
        Pattern pattern =  Pattern.compile("width=\".*?\"");
        Matcher m = pattern.matcher(imgStr);
        String width = "";
        String height = "";
        while(m.find()) {
            width = m.group().split("width=\"")[1].split("\"")[0].trim();
        }
        pattern =  Pattern.compile("height=\".*?\"");
        m = pattern.matcher(imgStr);
        while(m.find()) {
            height = m.group().split("height=\"")[1].split("\"")[0].trim();
        }
        if ("".equals(width)) {
            return "";
        }
        return width + " * " + height;
    }

    // 替换抓取新闻标题中可能出现的特殊字符
    private String replaceTitle(String title) {
        title = Tools.getDesc(title, "");
        title = title.replaceAll("\"", "&quot;").replaceAll(":", "&#58;");
        return title;
    }

    // 替换新闻内容中的html标签
    private String replaceContent(String html) {
        html = Tools.getDesc(html, "");
        html = html.toLowerCase();
        html = html.replaceAll("<p[^>]*?>", "<p>");
        html = html.replaceAll("<div[^>]*?>", "<p>");
        html = html.replaceAll("</div>", "</p>");
        html = html.replaceAll("<font[^>]*?>", "");
        html = html.replaceAll("<b(?!r)[^>]*?>", "");
        html = html.replaceAll("<span[^>]*?>","");
        html = html.replaceAll("</span>","");
        html = html.replaceAll("</font>","");
        html = html.replaceAll("<br[^>]*?>","<br/>");
        html = html.replaceAll("<style[^>]*?>[\\s\\S]*?<\\/style>","");
        html = html.replaceAll("<a[^>]*?>","");
        html = html.replaceAll("</a>", "");
        html = replaceTitle(html);
        int i = 0;
        while(html.indexOf("<img") > -1) {
            html = html.replaceFirst("<img[^>]*?>", "!--IMG#" + (i++)  + "--");
        }
        return html;
    }

    // 解析返回本地服务器地址集合
    private String imgs(org.jsoup.nodes.Element content) {
        Elements imgs = content.select("img");
        List<HashMap<String, String>> imgsJson = new ArrayList<HashMap<String, String>>();
        int size = imgs.size();
        for(int i = 0; i < size; i++) {
            String src = imgs.get(i).attr("src").toString();
            String pixel  = "550 * 366";
            String style = imgs.get(i).attr("style").toString();
            // 存入HashMap中
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("ref","!--IMG#" + i + "--");
            map.put("pixel", pixel);
            map.put("src", src);
            map.put("style", style);
            // 循环添加某篇新闻
            imgsJson.add(map);
        }
        return JSONUtil.toJson(imgsJson);
    }

    //获取验证码
    public Message toSms(Input input){
        Message msg = new Message("发送成功");
        String content = input.getDesc("content","");
        Integer hospital = input.getInt("hospital",-1);
        //医院
        List<Hospital> hospitalList =  QBuilder.db("basedb").queryHql("from hospital as hh where hh.name like \'%"+content+"%\'"+" and (hospital = 1070 or parent =1070)");
        //科室
        List<Dept> deptList =  QBuilder.db("basedb").queryHql("from Dept as dd where hospital in (select new map (hospital as h) from hospital as s where hospital = 1070 or parent =1070) and dd.deptName like '%"+ content +"%'");
        //医生
        List<User> userList =  QBuilder.db("basedb").queryHql("from User as u where hospital in (select new map (hospital as h) from hospital as s where hospital = 1070 or parent =1070) and u.name like '%"+ content +"%' and type = 200");

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("hospital",hospitalList);
        map.put("dept",deptList);
        map.put("doctor",userList);


        msg.put("data",map);
        //查询所有不记录
        if(content == null || content.equals("")){
            msg.put("errcode",0);
            msg.put("errmsg","查询完成");

            return msg;
        }

        //查询完成把搜索记录进行存储 （存在的更新搜索时间，不存在的进行增加。）


        List<Map> historyList = QBuilder.db("basedb").queryHql("select new map(id as id) from history_serch where  content = '"+ content+"'");//查询当前用户是否存在这个历史记录

        int num = 1;

        if(historyList == null || historyList.size() ==0){
            Map<String,Object> historyMap = new HashMap<String,Object>();

            // historyMap.put("uid",Integer.parseInt(uid));
            historyMap.put("content",content);
            historyMap.put("hospital",hospital);
            historyMap.put("create_time", System.currentTimeMillis());
            historyMap.put("status", STATUS_ENABLE);

            historyMap.put("json", "{}");

            DBTools.db("basedb").addItem("history_serch", historyMap);
        }else{

            String hql = "update history_serch set create_time ="+System.currentTimeMillis()+" where id = "+historyList.get(0).get("id")+"";
            num = QBuilder.db("basedb").execHQL(hql);
        }
        if(num == 0){
            msg.put("errcode",0);
            msg.put("errmsg","历史记录更新失败");

        }else{
            msg.put("errcode",0);
            msg.put("errmsg","查询完成");
        }
        return msg;
    }

    //新闻列表
    Message newsList(Input input) {

        Map map = new HashMap();
        Integer pageNum = input.getInt("page", 1); // 页码
        Integer itemCount = input.getInt("item_count", 12); // 每一页条目
        Integer category = input.getInt("category", 0); //新闻分类
        Integer status = input.getInt("status", 1); //新闻分类
        String table = "News n";
        String order = "desc"; // 排序
        String labelId = input.getDesc("labelId", "-1").replace(".0", ""); // 通过标签与新闻关联查询   不传默认通过category新闻类别查
        Where where = new Where("n.category=", category);

        if (pageNum <= 0 || itemCount <= 0) {
            return new Message(30041, "参数不合法，请输入正确的页码或限值");
        }
        String selectContent = "distinct new map(n.id as id , n.newsId as news_id, n.url as url, n.title as title, n.summary as summary, n.time as time, n.img as img, n.jsonString as json, n.category as category, n.author as author)" ;

        List newsList = QBuilder.db("basedb").select(selectContent).from("News as n").where(new Where("n.hospital=1111").and("n.category=", category).and("n.status = ", status)).page(itemCount, pageNum).order("n.newsId", order).query().getResultObj();
        List<Long> rankCount = QBuilder.db("basedb").select("count(*)").from(table).where(where.and("n.hospital=", "1111").and("n.status = ", status)).order("n.newsId", order).query().getResultObj();
        if (order.equals("asc")) { // 上拉加载时倒序
            Collections.reverse(newsList);
        }
        Message msg = new Message(0);
        Map resultMap = new HashMap();
        Long size = rankCount.get(0);
        resultMap.put("rank", newsList);
        resultMap.put("current_page", pageNum);
        resultMap.put("page_count",  size%itemCount == 0?(size/itemCount):(size/itemCount + 1));
        resultMap.put("count", size);
        msg.put("data", resultMap);
        return msg;
    }

    //设置已发布
    public Message setNews(Input input) {
        Message msg = new Message();

        String news_id = input.getDesc("news_id","39385").replace(".0","");
        Integer status = input.getInt("status",3);
        String hql = "update News set status = "+ status+" where id ="+news_id;
        int num = QBuilder.db("basedb").execHQL(hql);
        if(num == 0){
            return new Message(30041, "修改失败");
        }else{
            msg.put("errorcode",0);
            msg.put("errormsg","发不成功");
            msg.put("data",num);
        }
        return msg;
    }

    //批量发布
    public Message setNewsList(Input input) {
        Message msg = new Message();

        String news_ids = input.getDesc("news_ids","");
        Integer status = input.getInt("status",1);
        String hql = "update News set status = "+ status+" where  id in("+news_ids+")";
        int num = QBuilder.db("basedb").execHQL(hql);
        if(num == 0){
            return new Message(30041, "修改失败");
        }else{
            msg.put("errorcode",0);
            msg.put("errormsg","发布成功");
            msg.put("data",num);
        }
        return msg;
    }
    //展示新闻详情
    public Message news(Input input) {
        Message msg = new Message();
        Integer hospital = input.getInt("hospital", -1);    // 医院编号
        String news_id = input.getDesc("news_id","39385").replace(".0","");
        Integer status = input.getInt("status",1);
        List newsList = QBuilder.db("basedb").queryHql("from News where hospital="+hospital+" and status="+status+" and id="+news_id);
        if(newsList.size() == 0)
            return new Message(30041, "没有这条新闻");
        else
            msg.put("data", newsList.get(0));
        return msg;
    }

    // 添加新闻
    public Message addNews(Input input) {
        Message msg = new Message();
        Integer hospital = input.getInt("hospital", -1);    // 医院编号
        String deptCode = input.getDesc("deptCode","");
        String labelId = input.getDesc("labelId","").replace(".0","");
        String title = input.getDesc("title","");
        String author = input.getDesc("author","");
        String summary = input.getDesc("summary","");
        String content = input.getDesc("content","");
        //Map<String, String> imgMap = getImg(content,  PATTERN);
        Map jsonMap = new HashMap();
        jsonMap.put("attachs", new ArrayList());
        //获取时间
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sdf.format(cal.getTime());
        //新建新闻对象
        News news = new News();
        news.setTitle(title);
        news.setAuthor(author);
        news.setSummary(summary);
        news.setTime(time);
        news.setHospital(hospital);
        news.setCategory(Integer.valueOf(labelId));
        news.setBranch("dept-"+deptCode);
        news.setHtml(content);
        news.setImg(imgs(Jsoup.parse(content)));
        news.setContent(replaceContent(content));
        //news.setImg(Tools.getDesc(imgMap.get("imgs")));
        List<Map> imgs = JSONUtil.fromJson(news.getImg(), new TypeReference<List<Map>>(){});

        news.setJson(jsonMap);
        if (imgs.size() != 0 ) {
            System.out.println(imgs.get(0).get("src"));
            String url = ImageUtil.small(Tools.getDesc(imgs.get(0).get("src")));
            news.setJson("news_thumbnail", url);
        }
        try {
            DBTools.db("basedb").addItem(news);
            news.setNewsId(news.getId());
            DBTools.db("basedb").modItem(news,news.getId());
        } catch (Exception e) {
            e.printStackTrace();
            msg.setErrcodeAndErrmsg(30041, "新闻添加失败");
        }
        return msg;
    }

    // 删除新闻
    public Message deleteNews(Input input) {
        Message msg = new Message();
        Integer hospital = input.getInt("hospital", -1);    // 医院编号
        String newsId = input.getDesc("news_id","").replace(".0","");
        QBuilder.db("basedb").execHQL("update News set status= " + STATUS_DISABLE + " where hospital=" + hospital + " and id=" + newsId);
        return msg;
    }

    // 修改新闻
    public Message updateNews(Input input) {
        Message msg = new Message();
        Integer hospital = input.getInt("hospital", -1);    // 医院编号
        String newsId = input.getDesc("news_id","").replace(".0","");
        String title = input.getDesc("title","");
        String author = input.getDesc("author","");
        String content = input.getDesc("content","");
        Integer status = input.getInt("status",1);
        //  Map<String, String> imgMap = getImg(content,  PATTERN);
        Map jsonMap = new HashMap();
        jsonMap.put("attachs", new ArrayList());
        String summary = input.getDesc("summary","");
        List<News> list = QBuilder.db("basedb").queryHql("from News where hospital=" + hospital + " and id=" + newsId + " and status=" + status);
        if(list.size() == 0){
            return new Message(30041, "没有这条新闻");
        } else {
            News news = list.get(0);
            news.setTitle(title);
            news.setAuthor(author);
            news.setSummary(summary);
            news.setHtml(content);
            news.setImg(imgs(Jsoup.parse(content)));
            news.setContent(replaceContent(content));
            List<Map> imgs = JSONUtil.fromJson(news.getImg(), new TypeReference<List<Map>>(){});
            news.setJson(jsonMap);
            if (imgs.size() != 0 ) {
                String url = ImageUtil.small(Tools.getDesc(imgs.get(0).get("src")));
                news.setJson("news_thumbnail", url);
            }
            try {
                DBTools.db("basedb").modItem(news,news.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return msg;
    }

    /**
     * 查询科室接口
     * @param input
     * @return
     */
    public  Message getDept(Input input) {
        Message message  = new Message();
        Integer hospital = input.getInt("hospital", -1);    // 医院编号
        Integer type = input.getInt("type", 10);    // 类别  1 普通  5 预约
        List<Map> list;
        if(type == 5) {
            list = QBuilder.db("basedb").queryHql("select new map(id as id , deptName as deptName) from Dept where hospital=" + hospital + " and type=" + type + " and status=1 and parent!=-1");
        } else {
            list = QBuilder.db("basedb").queryHql("select new map(id as id , deptName as deptName) from Dept where hospital=" + hospital + " and type=" + type + " and status=1");
        }
        //List<Map> list = QBuilder.db("basedb").queryHql("select new map(id as id , deptName as deptName) from Dept where hospital=" + hospital + " and type=" + type + " and status=1 and parent!=-1");
        if(list == null || list.size() == 0){
            message.setErrcodeAndErrmsg(30041,"没有数据");
        }else{
            message.setErrcodeAndErrmsg(0,"查询完成");
            message.put("list",list);
        }
        return message;
    }
    /**
     * 查询根据科室分类 操作
     * @param input
     * @return
     */
    public Message queryByQuestion(Input input) {
        Message msg = new Message();
        Integer hospital = input.getInt("hospital", -1);    // 医院编号
        String deptId = input.getDesc("deptId","-1");

        String surveyTitle =  input.getDesc("surveyTitle","1");//分类名称
        String sHql = " select new map(id as id ) from Survey where hospital = "+hospital+" and title like '%"+surveyTitle+"%'";

        List<Map> surveyList =  QBuilder.db("basedb").queryHql(sHql);
        if(surveyList == null || surveyList.size() ==0 ){
            msg.put("errcode",30041);
            msg.put("errmsg","没有此分类");
//            Tools.encryptPrint(out,msg);
            return msg;
        }

        Integer surveyId = Integer.parseInt(surveyList.get(0).get("id").toString());
        String hql  = "" +
                "select new map(sa.questId as questId , sa.content as content ,count(sa.content) as count,so.showOrder as showOrder) from SurveyQuestion sq ,SurveyAnswer sa,SurveyOptions so" +
                " where sq.id = sa.questId  and sq.id = so.questId and sa.content=so.content     and  sq.hospital = "+hospital+
                " and sq.surveyId=" +surveyId+
                "  and sa.doctorUid ="+deptId+"  GROUP BY sa.questId,sa.doctorUid,sa.content ,sq.title " ;

        String hql2  = "" +
                "select new map(sa.questId as questId , sa.content as content ,count(sa.content) as count) from SurveyQuestion sq ,SurveyAnswer sa" +
                " where sq.id = sa.questId and sq.type=2     and  sq.hospital = "+hospital+
                " and sq.surveyId=" +surveyId+
                "  and sa.doctorUid ="+deptId+"  GROUP BY sa.questId,sa.doctorUid,sa.content ,sq.title " ;
        List<Map> mapList =  QBuilder.db("basedb").queryHql(hql);
        List<Map> mapList2 =  QBuilder.db("basedb").queryHql(hql2);
        mapList.addAll(mapList2);


        List<Map> quList =  QBuilder.db("basedb").queryHql("select new map(id as questId,sq.title as title ,sq.type as type) from SurveyQuestion sq where hospital="+hospital+" and sq.surveyId=" +surveyId+" order by showOrder");


        List<SurveyOptions> soList =  QBuilder.db("basedb").queryHql(" from SurveyOptions where hospital="+hospital);


        if(quList == null || quList.size() == 0 ){
            msg.put("errcode",30041);
            msg.put("errmsg","没有数据");


//            Tools.encryptPrint(out,msg);
            return msg;
        }

        for(Map map : quList){

            String questId = map.get("questId").toString();

            String type = map.get("type").toString();

            List<Map> childList = new ArrayList<Map>();
            Map<String,String> optinMap = new HashMap<String,String>();//存放已经有的选项
            int totalcount = 0;//统计总数量

            if(map.get("totalcount") != null ){
                String countStr = map.get("totalcount").toString();
                totalcount = Integer.parseInt(countStr);
            }
            for(Map anMap : mapList){
                String anQuestId = anMap.get("questId").toString();

                if(questId.equals(anQuestId)){
                    childList.add(anMap);

                    if(anMap.get("count") != null){
                        optinMap.put(anMap.get("content").toString(),anMap.get("count").toString());
                        int temp = Integer.parseInt(anMap.get("count").toString());
                        totalcount +=temp ;

                    }

                }
            }

            if(type != null && type.equals("1")){
                for(SurveyOptions so : soList){

                    if(questId.equals(so.getQuestId()+"")){//查看是否是同一道题
                        String temp =  optinMap.get(so.getContent());
                        if(temp == null || temp.equals("")){
                            Map<String,String> ma = new HashMap<String,String>();
                            ma.put("content",so.getContent());
                            ma.put("showOrder",so.getShowOrder()+"");
                            ma.put("count","0");
                            childList.add(ma);
                        }
                    }
                }
            }



            List<Map> finalChildList = new ArrayList<Map>();
            int i=0;
            while(true){
                for(Map temMap : childList) {
                    if(temMap.get("showOrder") == null){
                        finalChildList.add(temMap);
                        continue;
                    }
                    String showOrder = temMap.get("showOrder").toString();
//                System.out.println("showOrder:"+showOrder);
//                System.out.println("content:"+temMap.get("content").toString());
//                System.out.println("finalChildList:"+finalChildList.size());
                    if(showOrder.equals((finalChildList.size()+1)+"")){
                        finalChildList.add(temMap);
                    }

                }
                i++;
                if(i==2000 ||finalChildList.size() == childList.size()){
                    break;
                }

            }
            map.put("totalcount",totalcount);
            map.put("answer",finalChildList);


        }

        msg.put("errcode",0);
        msg.put("errmsg","查询完成");
        msg.put("data",quList);

//
        return msg;
    }
%>